import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/family.dart';

class FamilyScreen extends StatefulWidget {
  @override
  _FamilyScreenState createState() => _FamilyScreenState();
}

class _FamilyScreenState extends State<FamilyScreen> {
  List<Family> families = <Family>[];
  RefreshController _refreshController = RefreshController();
  int _loaded = 0;

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback((_) {
      _refreshController.requestRefresh();
    });
  }

  Future _getFamilies() async {
    List _list = await Family().fetch();
    setState(() {
      families.clear();
      _list.forEach((_item) => families.add(Family()..fromJson(_item)));
      int _loaded = 1;
    });
    _refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    TextEditingController _nickNameCtrl = new TextEditingController();

    return Scaffold(
      appBar: AppBar(
        title: Text('成员管理'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.camera_alt),
            onPressed: () {
              Navigator.pushNamed(context, '/scan');
            },
          )
        ],
      ),
      body: SmartRefresher(
          controller: _refreshController,
          onRefresh: _getFamilies,
          child: ListView.separated(
              separatorBuilder: listSeparatorBuilder,
              itemCount: families.length > 0 ? families.length : _loaded,
              itemBuilder: (BuildContext context, int index) {
                if (families.isEmpty)
                  return NoData(
                    content: '还没有成员哦,赶紧去加吧!',
                  );
                Family _family = families[index];
                return Slidable(
                  key: ValueKey(index),
                  child: ListTile(
                    title: Text(_family.nickname.toString().isEmpty ? '未设置' : _family.nickname),
                    subtitle: Text(_family.phone),
                    trailing: Icon(Icons.chevron_right),
                    onTap: () async {
                      _nickNameCtrl.text = _family.nickname;
                      String? res = await showDialog<String>(
                          context: context,
                          builder: (BuildContext context) {
                            return AlertDialog(
                              title: Text('请输入备注名称'),
                              content: TextField(
                                controller: _nickNameCtrl,
                                autofocus: true,
                              ),
                              actions: <Widget>[
                                TextButton(
                                  child: Text('提交'),
                                  onPressed: () {
                                    Navigator.of(context).pop(_nickNameCtrl.value.text);
                                    _nickNameCtrl.clear();
                                  },
                                ),
                              ],
                            );
                          });
                      if (res != null) {
                        setState(() {
                          _family.nickname = res;
                        });
                        await _family.store();
                      }
                    },
                  ),
                  endActionPane: ActionPane(
                    motion: const DrawerMotion(),
                    extentRatio: 0.25,
                    children: <Widget>[
                      SlidableAction(
                        label: '解除',
                        foregroundColor: Colors.white,
                        backgroundColor: Colors.red,
                        onPressed: (context) async {
                          final res = await showOkCancelAlertDialog(context: context, title: '确定解除?', message: '确定要解除关系吗?');
                          if (res == OkCancelResult.ok) {
                            await _family.delete();
                            setState(() {
                              families.removeAt(index);
                            });
                          }
                        },
                      ),
                    ],
                  ),
                );
              })),
    );
  }
}
